<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    @change="handleChange"
    :multiple="multiple"
    :clearable="clearable"
    :loading="isLoading"
    style="width: 100%"
  >
    <el-option
      v-for="option in options"
      :key="option.value"
      :label="option.name"
      :value="option.code"
    />
  </el-select>
</template>

<script>
import { getDictionaryItem } from "@/api/database";

export default {
  props: {
    value: {
      type: [String, Number, Array],
      default: null,
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    dataBaseCode: {
      type: String,
      default: "",
      required: true,
    },
  },
  data() {
    return {
      selectedValue: this.value,
      options: [],
      isLoading: false,
    };
  },
  watch: {
    value(newValue) {
      this.selectedValue = newValue;
    },
    selectedValue(newValue) {
      this.$emit("input", newValue);
    },
  },
  methods: {
    handleChange(value) {
      this.$emit("input", value);
    },
    async fetchOptions() {
      this.isLoading = true;
      try {
        const res = await getDictionaryItem({
          page: 1,
          size: 1000,
          dataBaseCode: this.dataBaseCode,
        });
        this.options = res.data;
      } catch (error) {
        console.error("获取选项数据失败:", error);
      } finally {
        this.isLoading = false;
      }
    },
  },
  created() {
    this.fetchOptions();
  },
};
</script>

<style scoped></style>
